package serverdb

import (
	"context"
	"fmt"
	"os"

	"github.com/golang-migrate/migrate/v4"
	"github.com/jackc/pgx/v4"
)

// Connect function return connection to psql database
func Connect(dbURL string) *pgx.Conn {
	conn, err := pgx.Connect(context.Background(), dbURL)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to connect to database: %v\n", err)
		os.Exit(1)
	}

	return conn
}

// Upgrade function upgrade database to latest version
func Upgrade(migrateURL string, dbURL string) error {
	m, err := migrate.New(migrateURL, dbURL)
	if err != nil {
		return err
	}
	err = m.Up()
	if err != nil {
		return err
	}
	return nil
}
